package com.shangke.corejava.ch13;
/**
 * 使用了线程的同步，解决了线程共享的问题，每个线程访问到的数据都是自己操作后的数据
 * @author admin
 *
 */
public class TestImport {
	private int count = 0;

	public synchronized void add(int threadId) {  //加的方法
		count++;
		System.out.println(threadId + " ," + count);
	}

	public synchronized void desc(int threadId) {  //减 的方法
		count--;
		System.out.println(threadId + " ," + count);
	}

	class AddClass implements Runnable {
		private int threadId = 0;

		public AddClass(int id) {
			this.threadId = id;
		}
		@Override
		public void run() {
			for (int i = 0; i < 50; i++) {
				add(threadId);  //使用加的方法，加的方法就是 count++
				//System.out.println(threadId + " ," + count);  //先加然后再输出
				try {
					Thread.sleep(100);
				} catch (InterruptedException e) {
				}
			}
		}
	}
	
	class DescClass implements Runnable {
		private int threadId = 0;

		public DescClass(int id) {
			this.threadId = id;
		}
		@Override
		public void run() {
			for (int i = 0; i < 50; i++) {
				desc(threadId);
				System.out.println(threadId + " ," + count);
				try {
					Thread.sleep(100);
				} catch (InterruptedException e) {
				}
			}
		}
	}
	public static void main(String[] args) {
		TestImport testImportAdd=new TestImport();
		
		AddClass AddClass=testImportAdd.new AddClass(1);
		AddClass addClass2=testImportAdd.new AddClass(2);
		
		DescClass descClass=testImportAdd.new DescClass(1);
		DescClass descClass2=testImportAdd.new DescClass(2);
		
		new Thread(AddClass).start();
		new Thread(addClass2).start();
		new Thread(descClass).start();
		new Thread(descClass2).start();
	}
}
